package hongcaosp.app.android.user.settings.update;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4;
import com.liulishuo.okdownload.core.listener.assist.Listener4Assist;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.List;
import java.util.Map;

import hongcaosp.app.android.R;
import hongcaosp.app.android.modle.bean.AppVersion;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.Util;

/**
 * 邀请码验证成功
 */
public class DialogUpdate extends Dialog {

    private LinearLayout ll_progress;
    private ProgressBar pb_progress;
    private TextView tv_progress,tv_content,tv_version;
    private Button btn_update;

    private AppVersion appVersion;

    public DialogUpdate(@NonNull Context context, AppVersion appVersion) {
        super(context);
        this.appVersion = appVersion;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setGravity(Gravity.CENTER);
        getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);

        setContentView(R.layout.dialog_update);

        ll_progress = findViewById(R.id.ll_progress);
        pb_progress = findViewById(R.id.pb_progress);
        tv_progress = findViewById(R.id.tv_progress);
        tv_version = findViewById(R.id.tv_version);
        tv_content = findViewById(R.id.tv_content);
        btn_update = findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndPermission.with(getContext())
                        .runtime()
                        .permission(Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                download(appVersion.getVersionUrl());
                            }
                        })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                ToastManager.getInstance().showToast("请给予我读写权限");
                            }
                        })
                        .start();
            }
        });
        tv_version.setText(appVersion.getVersionName());
        tv_content.setText(appVersion.getDescribe());
    }

    private long totalLength;
    private void download(String url) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.apk");
        if (file.exists()) {
            file.delete();
        }
        new DownloadTask.Builder(url,new File(Environment.getExternalStorageDirectory().getAbsolutePath()))
                .setFilename("temp.apk")
                .setMinIntervalMillisCallbackProcess(100)
                .setPassIfAlreadyCompleted(false)
                .build()
                .enqueue(new DownloadListener4() {

                    @Override
                    public void infoReady(DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4Assist.Listener4Model model) {
                        totalLength = info.getTotalLength();
                        pb_progress.setMax((int) (totalLength / 1024 / 1024));
                    }

                    @Override
                    public void progressBlock(DownloadTask task, int blockIndex, long currentBlockOffset) {

                    }

                    @Override
                    public void progress(DownloadTask task, long currentOffset) {
                        //下载进度
                        int now = (int) (currentOffset / 1024 / 1024);
                        int total = (int) (totalLength / 1024 / 1024);

                        pb_progress.setProgress(now);
                        tv_progress.setText("正在下载("+now+"/"+total+"M)");
                    }

                    @Override
                    public void blockEnd(DownloadTask task, int blockIndex, BlockInfo info) {

                    }

                    @Override
                    public void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause, @NonNull Listener4Assist.Listener4Model model) {
                        //下载完成
                        if (cause == EndCause.COMPLETED) {
                            dismiss();
                            Util.install(getContext(),task.getFile());
                        } else {
                            setCancelable(true);
                            setCanceledOnTouchOutside(true);

                            btn_update.setText("重新下载");
                            btn_update.setVisibility(View.VISIBLE);

                            ll_progress.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void taskStart(@NonNull DownloadTask task) {
                        setCancelable(false);
                        setCanceledOnTouchOutside(false);
                        btn_update.setVisibility(View.GONE);
                        ll_progress.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {

                    }

                    @Override
                    public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {

                    }
                });
    }
}
